﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Facebook;
using System.Dynamic;

namespace WpfApplication1
{
	/// <summary>
	/// Interaction logic for WindowDetail.xaml
	/// </summary>
	public partial class WindowDetail : Window
	{
        private string id;
		private string my_id;
		private string my_name;
        private CFacebookServer fbServer;
        private IDictionary<string, object> data; // Back up thong tin post
		private long offset = 0;
		private long limit = 25;

        public WindowDetail(string _id, string _my_id, string _my_name, double _Top, double _width, string AccessToken)
		{
			this.InitializeComponent();
            id = _id;
			my_id = _my_id;
			my_name = _my_name;
            fbServer = new CFacebookServer(AccessToken);
			// Insert code required on object creation below this point.
            this.Top = _Top;
            this.Left = SystemParameters.WorkArea.Width - this.Width - _width;
			this.MaxHeight = 616;
		}

		private void buttonexit_Click(object sender, System.Windows.RoutedEventArgs e)
		{
			// TODO: Add event handler implementation here.
			this.Close();
		}

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            LoadInfo();
        }
		
		private void LoadInfo()
		{
            IDictionary<string, object> source;
            try
            {
                source = (IDictionary<string, object>)fbServer.Get(id);
            }
            catch
            {
                source = null;
            }
            data = source;
            if (source == null)
            {
                MessageBox.Show("This object is not available!", "Error", MessageBoxButton.OK);
                this.Close();
                return;
            }
            if (source.ContainsKey("story"))
            {
                header.Text = (string)source["story"];
            } else {
                IDictionary<string, object> temp = (IDictionary<string, object>)source["from"];
                header.Text = (string)temp["name"];
            }
			IDictionary<string, object> profile = (IDictionary<string, object>)source["from"];
			BitmapImage bitmap = new BitmapImage();
            bitmap.BeginInit();
            string urlPic = string.Format("https://graph.facebook.com/{0}/picture?type={1}", (string)profile["id"], "square");
            bitmap.UriSource = new Uri(urlPic);
            bitmap.EndInit();
            profile_pic.Source = bitmap;
			
			// Load Message
			if (source.ContainsKey("message"))
			{
				message.Text = (string)source["message"];
			} else {
				message.Text = "";
				message.Visibility = Visibility.Collapsed;
			}
			// Load Picture if available
			if (source.ContainsKey("picture"))
			{
                string url = (string)source["picture"];
                url = url.Replace("_s", "_n");
				BitmapImage bm = new BitmapImage();
				bm.BeginInit();
                bm.UriSource = new Uri(url);
				bm.EndInit();
				picture.Source = bm;
			} else {
				picture.Visibility = Visibility.Collapsed;
			}
			// Load Caption
			if (source.ContainsKey("name"))
			{
				name.Text = (string)source["name"];
			} else {
				name.Visibility = Visibility.Collapsed;
			}
			// Load Description
			if (source.ContainsKey("description"))
			{
				description.Text = (string)source["description"];
			} else {
				description.Visibility = Visibility.Collapsed;
			}
			// Load Like & Comment count
			if (source.ContainsKey("likes"))
			{
				IDictionary<string, object> temp = (IDictionary<string, object>)source["likes"];
				like_counter.Text = temp["count"].ToString();
			} else {
				like_counter.Text = "0";
			}
			
			if (source.ContainsKey("comments"))
			{
				IDictionary<string, object> temp = (IDictionary<string, object>)source["comments"];
                if (temp.ContainsKey("count"))
                {
                    comment_counter.Text = temp["count"].ToString();
                    LoadComment((long)temp["count"]);
                }
                
			} else {
				comment_counter.Text = "0";
			}
			// Load Comment Post
			BitmapImage bm1 = new BitmapImage();
			bm1.BeginInit();
			urlPic = string.Format("https://graph.facebook.com/{0}/picture?type={1}", my_id, "square");
            bm1.UriSource = new Uri(urlPic);
			bm1.EndInit();
			pic_my_profile.Source = bm1;
			// Check CLink
			string type = (string)source["type"];
			if (type == "link")
			{
				onlylink.Cursor = Cursors.Hand;
				onlylink.ToolTip = "Go to link";
			}
			
		}
		
		void LoadComment(long comment_count)
		{
			string get_url;
            if (comment_count <= limit)
            {
                get_url = id + "/comments";
                ViewAllComments.Visibility = Visibility.Collapsed;
            }
            else
            {
                get_url = id + "/comments?offset=" + (comment_count - limit) + "&limit=" + limit;
                ViewAllComments.Visibility = Visibility.Visible;
            }
			
			IDictionary<string, object> comment_source = (IDictionary<string, object>)fbServer.Get(get_url);
            List<object> comment_data = (List<object>)comment_source["data"];
			List<object> comment_result = new List<object>();
            for (int i = 0; i < comment_data.Count; i++)
            {
                CComment temp = new CComment();
                IDictionary<string, object> temp_data = (IDictionary<string, object>)comment_data[i];
                temp.id = (string)temp_data["id"];
                temp.message = (string)temp_data["message"];
                temp.from = (IDictionary<string, object>)temp_data["from"];
                temp.created_time = (string)temp_data["created_time"];
				comment_result.Add(temp);
            }
            list_comments.ItemsSource = comment_result;
		}

		private void post_message_GotFocus(object sender, System.Windows.RoutedEventArgs e)
		{
			// TODO: Add event handler implementation here.
			if (post_message.Text == "Enter your comment")
			{
				post_message.Text = "";
				post_message.FontStyle = FontStyles.Normal;
			}
		}

		private void post_message_LostFocus(object sender, System.Windows.RoutedEventArgs e)
		{
			// TODO: Add event handler implementation here.
			if (post_message.Text == "")
			{
				post_message.Text = "Enter your comment";
				post_message.FontStyle = FontStyles.Italic;
			}
		}

        private void post_message_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            // TODO: Add event handler implementation here


            if ((e.KeyboardDevice.Modifiers == ModifierKeys.None) && e.Key == Key.Enter)
            {
                // Do post message to facebook
                e.Handled = true;
                PostMessage();
            }
        }
		private void PostMessage()
		{
            if (post_message.Text == "")
            {
                MessageBox.Show("Your message must not be empty");
                return;
            }
            dynamic paramenters = new ExpandoObject();
            paramenters.message = post_message.Text;
            string result = fbServer.Post(id + "/comments", paramenters);
            if (result != null)
            {
                MessageBox.Show("Message has been posted successfully!");
                // Reload messages
                IDictionary<string, object> temp = (IDictionary<string, object>)fbServer.Get(result);
                List<object> temp2 = new List<object>();

                temp2 = (List<object>)list_comments.ItemsSource;

                CComment temp_comment = new CComment();
                temp_comment.id = result;
                temp_comment.message = (string)temp["message"];
                temp_comment.from = (IDictionary<string, object>)temp["from"];
                temp_comment.created_time = (string)temp["created_time"];

                temp2.Add(temp_comment);
                list_comments.ItemsSource = temp2;
                post_message.Text = "";
                list_comments.Items.Refresh();
                list_comments.Focus(); // De hien lai chu 'Enter your message'
            }
            else
            {
                MessageBox.Show("Can not post your message!");
            }

		}

		private void ImageLike_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			// TODO: Add event handler implementation here.
            string result = fbServer.PostLike(id);
            if (result != "true")
            {
                if (like_counter.Text == "0")
                    like_counter.Text = "You like this";
                else
                    like_counter.Text = "You and " + like_counter.Text + " other people(s) like this";
            } else {
                MessageBox.Show("Can not like this post!");
            }
		}

		private void ViewAllComment_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			// TODO: Add event handler implementation here.
			IDictionary<string, object> temp1 = (IDictionary<string, object>)data["comments"];
			string get_url = id + "/comments?"+"limit=99999999";
			MessageBox.Show(get_url);
			IDictionary<string, object> comment_source = (IDictionary<string, object>)fbServer.Get(get_url);
            List<object> comment_data = (List<object>)comment_source["data"];
			List<object> comment_result = new List<object>();
            for (int i = 0; i < comment_data.Count; i++)
            {
                CComment temp = new CComment();
                IDictionary<string, object> temp_data = (IDictionary<string, object>)comment_data[i];
                temp.id = (string)temp_data["id"];
                temp.message = (string)temp_data["message"];
                temp.from = (IDictionary<string, object>)temp_data["from"];
                temp.created_time = (string)temp_data["created_time"];
				comment_result.Add(temp);
            }
            list_comments.ItemsSource = comment_result;

            ViewAllComments.Visibility = Visibility.Collapsed;
		}

		private void Linking_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			// TODO: Add event handler implementation here.
            // Mở post trên cửa sổ mới
			List<object> temp = (List<object>)data["actions"];
			IDictionary<string, object> temp2 = (IDictionary<string, object>)temp[0];
			string link = (string)temp2["link"];
            //
			System.Diagnostics.Process.Start(link);
			this.Close();
		}

		private void onlylink_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
		{
			// TODO: Add event handler implementation here.
			if ((string)data["type"] == "link")
			{
				string link = (string)data["link"];
				System.Diagnostics.Process.Start(link);
				this.Close();
			}
		}
        
        
	}
}